<template>
  <el-main>
    <el-row :gutter="20" style="height: calc(100vh - 120px);">
      <!-- 左侧部门树 -->
      <el-col :span="8">
        <el-card class="tree-card">
          <template #header>
            <div class="card-header">
              <span>部门层级</span>
              <el-button type="primary" size="small" @click="handleAddRoot">
                <el-icon><Plus /></el-icon>
                添加根部门
              </el-button>
            </div>
          </template>
          <el-tree
            ref="treeRef"
            :data="departmentTree"
            :props="treeProps"
            node-key="id"
            :default-expand-all="true"
            :highlight-current="true"
            @node-click="handleNodeClick"
            v-loading="treeLoading"
          >
            <template #default="{ node, data }">
              <div class="tree-node">
                <span class="node-label">{{ data.name }}</span>
                <div class="node-actions">
                  <el-button
                    type="primary"
                    size="small"
                    link
                    @click.stop="handleAddChild(data)"
                  >
                    <el-icon><Plus /></el-icon>
                  </el-button>
                  <el-button
                    type="primary"
                    size="small"
                    link
                    @click.stop="handleEdit(data)"
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button
                    type="danger"
                    size="small"
                    link
                    @click.stop="handleDelete(data)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
              </div>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧部门列表 -->
      <el-col :span="16">
        <el-card class="list-card">
          <template #header>
            <div class="card-header">
              <span>{{ selectedDeptName ? `${selectedDeptName} - 下级部门` : '请选择部门' }}</span>
              <el-button 
                type="primary" 
                size="small" 
                @click="handleAddChild(selectedDept)"
                :disabled="!selectedDept"
              >
                <el-icon><Plus /></el-icon>
                添加下级部门
              </el-button>
            </div>
          </template>

          <!-- 搜索表单 -->
          <el-form
            ref="searchRef"
            :model="searchParam"
            :inline="true"
            class="search-form"
          >
            <el-form-item label="部门名称" prop="name">
              <el-input
                v-model="searchParam.param.name"
                placeholder="请输入部门名称"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="部门编码" prop="code">
              <el-input
                v-model="searchParam.param.code"
                placeholder="请输入部门编码"
                clearable
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select
                v-model="searchParam.param.status"
                placeholder="请选择状态"
                clearable
                style="width: 120px"
              >
                <el-option label="全部" :value="undefined" />
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                搜索
              </el-button>
              <el-button @click="handleReset">
                <el-icon><Refresh /></el-icon>
                重置
              </el-button>
            </el-form-item>
          </el-form>

          <!-- 表格 -->
          <el-table
            :data="tableData"
            v-loading="tableLoading"
            style="width: 100%"
            height="400"
          >
            <el-table-column prop="name" label="部门名称" width="150" />
            <el-table-column prop="code" label="部门编码" width="120" />
            <el-table-column prop="level" label="层级" width="80" />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                  {{ row.status === 1 ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" show-overflow-tooltip />
            <el-table-column prop="createTime" label="创建时间" width="180" />
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="handleEdit(row)">
                  编辑
                </el-button>
                <el-button type="success" size="small" @click="handleAddChild(row)">
                  添加下级
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="searchParam.curPage"
              v-model:page-size="searchParam.pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="searchParam.total"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 部门表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入部门编码" />
        </el-form-item>
        <el-form-item label="父级部门" prop="parentId">
          <el-tree-select
            v-model="formData.parentId"
            :data="departmentTree"
            :props="treeProps"
            placeholder="请选择父级部门"
            check-strictly
            clearable
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formData.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </el-main>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus';
import { Plus, Edit, Delete, Search, Refresh } from '@element-plus/icons-vue';
import { 
  getDepartmentTree, 
  getDepartmentListByParentId, 
  addDepartment, 
  updateDepartment, 
  deleteDepartment 
} from '@/api/department';
import type { Department, DepartmentQuery, DepartmentForm } from '@/api/department/DepartmentModel';

// 响应式数据
const treeRef = ref();
const searchRef = ref<FormInstance>();
const formRef = ref<FormInstance>();

// 树形数据
const departmentTree = ref<Department[]>([]);
const treeLoading = ref(false);
const treeProps = {
  children: 'children',
  label: 'name'
};

// 选中的部门
const selectedDept = ref<Department | null>(null);
const selectedDeptName = ref('');

// 表格数据
const tableData = ref<Department[]>([]);
const tableLoading = ref(false);

// 搜索参数
const searchParam = reactive<DepartmentQuery>({
  curPage: 1,
  pageSize: 10,
  total: 0,
  pages: 0,
  param: {
    name: '',
    code: '',
    status: undefined,
    parentId: null
  }
});

// 对话框
const dialogVisible = ref(false);
const dialogTitle = ref('');
const submitLoading = ref(false);

// 表单数据
const formData = reactive<DepartmentForm>({
  name: '',
  code: '',
  parentId: null,
  level: 1,
  sort: 0,
  status: 1,
  remark: ''
});

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入部门编码', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序', trigger: 'blur' }
  ]
};

// 获取部门树
const loadDepartmentTree = async () => {
  try {
    treeLoading.value = true;
    const response = await getDepartmentTree();
    departmentTree.value = response.data || [];
  } catch (error) {
    ElMessage.error('获取部门树失败');
  } finally {
    treeLoading.value = false;
  }
};

// 获取部门列表
const loadDepartmentList = async () => {
  if (!selectedDept.value) {
    tableData.value = [];
    return;
  }

  try {
    tableLoading.value = true;
    const params = {
      ...searchParam,
      param: {
        ...searchParam.param,
        parentId: selectedDept.value.id
      }
    };
    const response = await getDepartmentListByParentId(selectedDept.value.id, params);
    tableData.value = response.data.records || [];
    searchParam.total = response.data.total || 0;
    searchParam.pages = response.data.pages || 0;
  } catch (error) {
    ElMessage.error('获取部门列表失败');
  } finally {
    tableLoading.value = false;
  }
};

// 树节点点击事件
const handleNodeClick = (data: Department) => {
  selectedDept.value = data;
  selectedDeptName.value = data.name;
  searchParam.curPage = 1;
  loadDepartmentList();
};

// 搜索
const handleSearch = () => {
  searchParam.curPage = 1;
  loadDepartmentList();
};

// 重置
const handleReset = () => {
  searchRef.value?.resetFields();
  searchParam.curPage = 1;
  loadDepartmentList();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  searchParam.pageSize = val;
  searchParam.curPage = 1;
  loadDepartmentList();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  searchParam.curPage = val;
  loadDepartmentList();
};

// 添加根部门
const handleAddRoot = () => {
  dialogTitle.value = '添加根部门';
  resetForm();
  formData.parentId = null;
  formData.level = 1;
  dialogVisible.value = true;
};

// 添加子部门
const handleAddChild = (data: Department) => {
  dialogTitle.value = '添加子部门';
  resetForm();
  formData.parentId = data.id;
  formData.level = data.level + 1;
  dialogVisible.value = true;
};

// 编辑部门
const handleEdit = (data: Department) => {
  dialogTitle.value = '编辑部门';
  Object.assign(formData, data);
  dialogVisible.value = true;
};

// 删除部门
const handleDelete = async (data: Department) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除部门"${data.name}"吗？删除后不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    await deleteDepartment(data.id);
    ElMessage.success('删除成功');
    
    // 刷新数据
    await loadDepartmentTree();
    if (selectedDept.value?.id === data.id) {
      selectedDept.value = null;
      selectedDeptName.value = '';
      tableData.value = [];
    } else {
      loadDepartmentList();
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    name: '',
    code: '',
    parentId: null,
    level: 1,
    sort: 0,
    status: 1,
    remark: ''
  });
  formRef.value?.clearValidate();
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    submitLoading.value = true;
    
    if (formData.id) {
      await updateDepartment(formData);
      ElMessage.success('更新成功');
    } else {
      await addDepartment(formData);
      ElMessage.success('添加成功');
    }
    
    dialogVisible.value = false;
    await loadDepartmentTree();
    loadDepartmentList();
  } catch (error) {
    ElMessage.error(formData.id ? '更新失败' : '添加失败');
  } finally {
    submitLoading.value = false;
  }
};

// 初始化
onMounted(() => {
  loadDepartmentTree();
});
</script>

<style scoped>
.tree-card,
.list-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tree-node {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding-right: 8px;
}

.node-label {
  flex: 1;
}

.node-actions {
  display: flex;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.tree-node:hover .node-actions {
  opacity: 1;
}

.search-form {
  margin-bottom: 16px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 16px;
}

:deep(.el-tree-node__content) {
  height: 32px;
}

:deep(.el-tree-node__label) {
  font-size: 14px;
}
</style>
